import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

export const useUpload = () => {
  const uploadVisible = ref(false)
  const tableData = reactive([])
  const tableHeader = reactive([])

  const uploadAction = () => {
    uploadVisible.value = true
  }

  const closeUpload = () => {
    uploadVisible.value = false
    tableHeader.length = 0
    tableData.length = 0
  }
  const beforeUpload = (file) => {
    const isLt1M = file.size / 1024 / 1024 < 1

    if (isLt1M) {
      return true
    }

    ElMessage({
      message: '请不要上传超过1MB的文件.',
      type: 'warning'
    })
    return false
  }

  const handleSuccess = ({ results, header }) => {
    tableData.length = 0
    Object.assign(tableData, results)
    tableHeader.length = 0
    Object.assign(tableHeader, header)
  }

  return {
    uploadVisible,
    tableHeader,
    tableData,
    uploadAction,
    closeUpload,
    beforeUpload,
    handleSuccess
  }
}
